package com.example.audiowebviewdemo;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private EditText editStreamUrl;
    private Button btnStartTest;
    private Button btnPlay;
    private Button btnPause;
    private Button btnStop;
    private ProgressBar progressBar;
    private TextView textProgress;
    private TextView textStatus;
    private TextView textLog;
    
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable progressUpdateRunnable;
    private boolean isPlaying = false;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化 UI 控件
        initViews();
        
        // 初始化 WebView（隐藏，仅作为播放器）
        webView = findViewById(R.id.webView);
        setupWebView();

        // 加载本地 HTML 文件
        webView.loadUrl("file:///android_asset/audio_player.html");
    }

    private void initViews() {
        editStreamUrl = findViewById(R.id.editStreamUrl);
        btnStartTest = findViewById(R.id.btnStartTest);
        btnPlay = findViewById(R.id.btnPlay);
        btnPause = findViewById(R.id.btnPause);
        btnStop = findViewById(R.id.btnStop);
        progressBar = findViewById(R.id.progressBar);
        textProgress = findViewById(R.id.textProgress);
        textStatus = findViewById(R.id.textStatus);
        textLog = findViewById(R.id.textLog);

        // 设置按钮点击事件
        btnStartTest.setOnClickListener(v -> startTest());
        btnPlay.setOnClickListener(v -> playAudio());
        btnPause.setOnClickListener(v -> pauseAudio());
        btnStop.setOnClickListener(v -> stopAudio());
    }

    private void setupWebView() {
        WebSettings webSettings = webView.getSettings();

        // 启用 JavaScript
        webSettings.setJavaScriptEnabled(true);

        // 启用 DOM 存储
        webSettings.setDomStorageEnabled(true);

        // 启用数据库存储
        webSettings.setDatabaseEnabled(true);

        // WebView 会自动管理缓存，无需额外启用 AppCache（已废弃）

        // 允许访问文件
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);

        // 启用媒体播放
        webSettings.setMediaPlaybackRequiresUserGesture(false);

        // 设置缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

        // 添加 JavaScript 接口
        webView.addJavascriptInterface(new WebAppInterface(), "Android");

        // 设置 WebViewClient
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                addLog("WebView 页面加载完成");
                updateStatus("准备就绪", "#e8f5e9", "#388e3c");
            }
        });

        // 设置 WebChromeClient（用于处理音频播放权限等）
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(android.webkit.ConsoleMessage consoleMessage) {
                // 在 Logcat 中输出 JavaScript 控制台消息
                android.util.Log.d("WebView", consoleMessage.message() + " -- From line "
                        + consoleMessage.lineNumber() + " of "
                        + consoleMessage.sourceId());
                // 同时显示在 UI 上
                addLog(consoleMessage.message());
                return super.onConsoleMessage(consoleMessage);
            }
        });
    }

    // JavaScript 接口类
    public class WebAppInterface {
        @JavascriptInterface
        public void onAudioReady() {
            runOnUiThread(() -> {
                addLog("✓ 音频已准备好");
                updateStatus("音频已准备好，可以播放", "#e8f5e9", "#388e3c");
                btnStartTest.setEnabled(true);
                btnPlay.setEnabled(true);
                btnPause.setEnabled(true);
                btnStop.setEnabled(true);
            });
        }

        @JavascriptInterface
        public void onAudioPlay() {
            runOnUiThread(() -> {
                isPlaying = true;
                addLog("▶ 开始播放");
                updateStatus("正在播放...", "#e8f5e9", "#388e3c");
                startProgressUpdate();
            });
        }

        @JavascriptInterface
        public void onAudioPause() {
            runOnUiThread(() -> {
                isPlaying = false;
                addLog("⏸ 暂停播放");
                updateStatus("已暂停", "#fff3e0", "#f57c00");
                stopProgressUpdate();
            });
        }

        @JavascriptInterface
        public void onAudioEnd() {
            runOnUiThread(() -> {
                isPlaying = false;
                addLog("■ 播放结束");
                updateStatus("播放结束", "#e3f2fd", "#1976d2");
                stopProgressUpdate();
                progressBar.setProgress(0);
                textProgress.setText("00:00 / 00:00");
                btnStartTest.setEnabled(true);
                btnPlay.setEnabled(false);
                btnPause.setEnabled(false);
                btnStop.setEnabled(false);
            });
        }

        @JavascriptInterface
        public void onAudioError(String error) {
            runOnUiThread(() -> {
                isPlaying = false;
                addLog("✗ 播放错误: " + error);
                updateStatus("播放出错: " + error, "#ffebee", "#c62828");
                stopProgressUpdate();
                btnStartTest.setEnabled(true);
                btnPlay.setEnabled(false);
                btnPause.setEnabled(false);
                btnStop.setEnabled(false);
            });
        }

        @JavascriptInterface
        public void onAudioMetadataLoaded(double duration) {
            runOnUiThread(() -> {
                addLog("✓ 音频元数据已加载，时长: " + formatTime((long)duration) + " 秒");
            });
        }

        @JavascriptInterface
        public void onAudioLoadStart() {
            runOnUiThread(() -> {
                addLog("✓ 开始加载音频");
                updateStatus("正在加载...", "#e3f2fd", "#1976d2");
            });
        }
    }

    // 开始测试
    private void startTest() {
        String streamUrl = editStreamUrl.getText().toString().trim();

        if (streamUrl.isEmpty()) {
            updateStatus("请输入流链接 URL", "#ffebee", "#c62828");
            addLog("✗ 错误: 流链接 URL 不能为空");
            return;
        }

        addLog("========== 开始测试 ==========");
        addLog("流链接: " + streamUrl);
        addLog("提示: Audio 会自动识别 MIME 类型");

        // 调用 JavaScript 函数开始播放（不需要 MIME 类型）
        String js = String.format(
            "startAudio('%s');",
            streamUrl.replace("'", "\\'")
        );
        webView.evaluateJavascript(js, null);

        // 禁用开始测试按钮，启用控制按钮
        btnStartTest.setEnabled(false);
        btnPlay.setEnabled(false);
        btnPause.setEnabled(false);
        btnStop.setEnabled(false);
    }

    // 播放音频
    private void playAudio() {
        webView.evaluateJavascript("playAudio();", null);
    }

    // 暂停音频
    private void pauseAudio() {
        webView.evaluateJavascript("pauseAudio();", null);
    }

    // 停止音频
    private void stopAudio() {
        webView.evaluateJavascript("stopAudio();", null);
        isPlaying = false;
        stopProgressUpdate();
        progressBar.setProgress(0);
        textProgress.setText("00:00 / 00:00");
        updateStatus("已停止", "#e3f2fd", "#1976d2");
        addLog("■ 停止播放");
        btnStartTest.setEnabled(true);
        btnPlay.setEnabled(false);
        btnPause.setEnabled(false);
        btnStop.setEnabled(false);
    }

    // 更新进度
    private void startProgressUpdate() {
        stopProgressUpdate();
        progressUpdateRunnable = new Runnable() {
            @Override
            public void run() {
                if (isPlaying) {
                    // 获取当前播放时间和总时长
                    webView.evaluateJavascript(
                        "getAudioProgress();",
                        value -> {
                            if (value != null && !value.equals("null")) {
                                // value 格式: "currentTime,duration"
                                String[] parts = value.replace("\"", "").split(",");
                                if (parts.length == 2) {
                                    try {
                                        double currentTime = Double.parseDouble(parts[0]);
                                        double duration = Double.parseDouble(parts[1]);
                                        
                                        runOnUiThread(() -> {
                                            if (duration > 0) {
                                                int progress = (int) ((currentTime / duration) * 100);
                                                progressBar.setProgress(progress);
                                                textProgress.setText(
                                                    formatTime((long)currentTime) + " / " + formatTime((long)duration)
                                                );
                                            }
                                        });
                                    } catch (NumberFormatException e) {
                                        // 忽略解析错误
                                    }
                                }
                            }
                        }
                    );
                    handler.postDelayed(this, 500); // 每 500ms 更新一次
                }
            }
        };
        handler.post(progressUpdateRunnable);
    }

    private void stopProgressUpdate() {
        if (progressUpdateRunnable != null) {
            handler.removeCallbacks(progressUpdateRunnable);
            progressUpdateRunnable = null;
        }
    }

    // 格式化时间
    private String formatTime(long seconds) {
        long minutes = seconds / 60;
        long secs = seconds % 60;
        return String.format("%02d:%02d", minutes, secs);
    }

    // 添加日志
    private void addLog(String message) {
        String timestamp = new java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault())
                .format(new java.util.Date());
        String logEntry = "[" + timestamp + "] " + message + "\n";
        textLog.append(logEntry);
        // 自动滚动到底部
        android.util.Log.d("AudioPlayer", message);
    }

    // 更新状态
    private void updateStatus(String status, String bgColor, String textColor) {
        textStatus.setText(status);
        textStatus.setBackgroundColor(android.graphics.Color.parseColor(bgColor));
        textStatus.setTextColor(android.graphics.Color.parseColor(textColor));
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            stopProgressUpdate();
            webView.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) {
            webView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) {
            webView.onResume();
        }
    }
}

